package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.CaptchaUtil;
import com.example.lotterysystem.common.utils.RedisUtil;
import com.example.lotterysystem.common.utils.RegexUtil;
import com.example.lotterysystem.service.SmsService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author xuejiao
 * Data 2025/4/30 12:33
 */
@Service
public class SmsServiceImpl implements SmsService {

    //对于redis里面的key需要标准化，为了区分业务
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void sendSms(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        //2.生成随机验证码
        String code = CaptchaUtil.getCaptcha(4);
        // 3.模拟发送短信验证码
        System.out.println("模拟发送短信到 " + phoneNumber + "验证码为："+code);
        // 4.缓存到redis
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,
                code,VERIFICATION_CODE_TIMEOUT);

    }

    @Override
    public String getSms(String phoneNumber) {
        //1.校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        return redisUtil.get(VERIFICATION_CODE_PREFIX+ phoneNumber);
    }
}
